package ynu.edu.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 全局日志过滤器
 * 记录所有通过网关的请求信息
 */
@Component
public class LoggingGlobalFilter implements GlobalFilter, Ordered {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        
        String timestamp = LocalDateTime.now().format(FORMATTER);
        String method = request.getMethod().name();
        String path = request.getURI().getPath();
        String query = request.getURI().getQuery();
        String remoteAddress = request.getRemoteAddress() != null ? 
            request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
        
        // 记录请求开始时间
        long startTime = System.currentTimeMillis();
        
        System.out.println(String.format(
            "📝 [%s] 请求开始 - %s %s%s - 来源IP: %s", 
            timestamp, method, path, 
            query != null ? "?" + query : "",
            remoteAddress
        ));
        
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 记录请求结束时间和耗时
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            
            int statusCode = exchange.getResponse().getStatusCode() != null ? 
                exchange.getResponse().getStatusCode().value() : 0;
            
            System.out.println(String.format(
                "✅ [%s] 请求完成 - %s %s - 状态码: %d - 耗时: %dms", 
                LocalDateTime.now().format(FORMATTER), method, path, statusCode, duration
            ));
        }));
    }

    @Override
    public int getOrder() {
        // 设置最高优先级，确保日志过滤器是第一个执行的
        return Ordered.HIGHEST_PRECEDENCE;
    }
} 